package com.ssw.core.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 孙常胜
 * @CreateTime: 2021/8/2 15:32
 * @Description:
 */
@Log4j2
@RestController
@RequestMapping("test")
public class Test {

    @RequestMapping("get")
    public String get() {
        String result = "";
        String resource = "get";
        initFlowRules(resource, 2);
        try (Entry entry = SphU.entry(resource)) {
            result = "success";
        } catch (Exception e) {
            result = "访问过于频繁";
        }
        log.info("返回结果：{}", result);
        return result;
    }

    @RequestMapping("set")
    public String set(){
        return "set";
    }
    /**
     * 定义规则
     * @param resource 资源名
     * @param count    qps 1秒最多多少个请求
     */
    private static void initFlowRules(String resource, int count) {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource(resource);
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setCount(count);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }
}


